package com.kygeng.springframework.aop.aspectj;

import com.kygeng.springframework.aop.ClassFilter;
import com.kygeng.springframework.aop.MethodMatcher;
import com.kygeng.springframework.aop.Pointcut;
import org.aspectj.weaver.tools.PointcutExpression;
import org.aspectj.weaver.tools.PointcutParser;
import org.aspectj.weaver.tools.PointcutPrimitive;

import java.lang.reflect.Method;
import java.util.HashSet;
import java.util.Set;

/**
 * @Title: AspectJExpressionPointcut
 * @Author: kygeng
 * @Package: com.kygeng.springframework.aop.aspectj
 * @Date: 2024/8/10 15:15
 * @Description: 实现切点表达式类
 */
public class AspectJExpressionPointcut implements Pointcut, ClassFilter, MethodMatcher {

    //PointcutPrimitive(Pointcut基元):标准的AspectJ Aop的pointcut的表达式类型
    private static final Set<PointcutPrimitive> SUPPORTED_PRIMITIVES = new HashSet<PointcutPrimitive>();

    static {
        SUPPORTED_PRIMITIVES.add(PointcutPrimitive.EXECUTION);//execution：一般用于指定方法的执行，用的最多
    }

    //切点表达式
    private final PointcutExpression pointcutExpression;

    public AspectJExpressionPointcut(String expression) {
        //返回一个切入点分析器，该分析器可以分析从 AspectJ 支持的 用户定义的PointcutPrimitive子集构建的切入点表达式。
        PointcutParser pointcutParser = PointcutParser.getPointcutParserSupportingSpecifiedPrimitivesAndUsingSpecifiedClassLoaderForResolution(SUPPORTED_PRIMITIVES, this.getClass().getClassLoader());
        pointcutExpression = pointcutParser.parsePointcutExpression(expression);
    }

    @Override
    public boolean matches(Class<?> clazz) {
        return pointcutExpression.couldMatchJoinPointsInType(clazz);
    }

    @Override
    public boolean matches(Method method, Class<?> targetClass) {
        return pointcutExpression.matchesMethodExecution(method).alwaysMatches();
    }

    @Override
    public ClassFilter getClassFilter() {
        return this;
    }

    @Override
    public MethodMatcher getMethodMatcher() {
        return this;
    }
}
